<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class JourneySubscribers extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectJourneySubscribers($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectJourneySubscribers($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values)
                || !array_key_exists('id_journey', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $query = "SELECT uj.id_user
                      FROM user_journeys uj
                      WHERE uj.id_journey = {$values['id_journey']}
                      AND uj.id_user <> {$values['id_user']}";

            $db_handle = @pg_pconnect(dbutils::$conn_string);
            $result = @pg_query($db_handle, $query);
            if ($result)
                $result = dbutils::dbresult_to_json($result);
            else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>